import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:iea/utils/date_util.dart';
import 'package:iea/provider/base/base_resp.dart';
import 'package:iea/blocs/personalCenterPage_blocs/personalCenter_bloc.dart';
import 'package:iea/blocs/personalCenterPage_blocs/uploadAvatar_bloc.dart';

class PersonalCenter extends StatefulWidget {
  @override
  _PersonalCenterState createState() => _PersonalCenterState();
}

class _PersonalCenterState extends State<PersonalCenter> {
  String lastSelectedValue;
  String msgValue;
  String _sex = '请选择';
  String _sexValue = '3';
  String _nickName = '';
  // String _birth = '请选择';
  double _kPickerSheetHeight = 216.0;
  DateTime date = DateTime.now();
  File _image;
  String backImageUrl = '';

  UploadAvatarBloc _bloc = new UploadAvatarBloc();
  PersonalPageBloc _savebloc = new PersonalPageBloc();

  _uploadImgUrl(FormData formData) {
    _bloc.upLoadAvatar(formData);
  }

  _save(params) {
    _savebloc.updateUserInformation(params);
  }

  // 获取相机
  Future getCameraImage() async {
    // 从相机获取照片
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    // 裁剪
    var croppedFile = await _cropImage(image);
    // 压缩
    var compressFile = await _zipImg(croppedFile);
    // 上传
    _uploadImage(compressFile);

    setState(() {
      _image = compressFile;
    });

    Navigator.pop(context);
  }

  // 获取相册
  Future getGalleryImage() async {
    // 从相册选照片
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    // 裁剪
    var croppedFile = await _cropImage(image);
    // 压缩
    var compressFile = await _zipImg(croppedFile);
    // 上传
    _uploadImage(compressFile);

    setState(() {
      _image = compressFile;
    });

    Navigator.pop(context);
  }

  // 裁剪图片
  _cropImage(File imageFile) async {
    File croppedFile = await ImageCropper.cropImage(
      sourcePath: imageFile.path,
      ratioX: 1.0,
      ratioY: 1.0,
      maxWidth: 512,
      maxHeight: 512,
    );
    return croppedFile;
  }

  // 压缩图片
  Future<File> _zipImg(File imageFile) async {
    File compressFile = await FlutterImageCompress.compressAndGetFile(
        imageFile.path, imageFile.path,
        quality: 90);
    return compressFile;
  }

  // actionsheet 组件方法
  void showPersonalActionSheet({BuildContext context, Widget child}) {
    showCupertinoModalPopup<String>(
      context: context,
      builder: (BuildContext context) => child,
    ).then((String value) {
      if (value != null) {
        setState(() {
          lastSelectedValue = value;
        });
      }
    });
  }

  // 错误弹窗
  void showMsgDialog({BuildContext context, Widget child}) {
    showCupertinoDialog<String>(
      context: context,
      builder: (BuildContext context) => child,
    ).then((String value) {
      if (value != null) {
        setState(() {
          msgValue = value;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          leading: IconButton(
              icon: Icon(Icons.arrow_back_ios, color: Color(0xFF4A4A4A)),
              onPressed: () {
                Navigator.pop(context);
              }),
          title: Text('个人信息', style: TextStyle(color: Colors.black)),
          actions: <Widget>[
            StreamBuilder(
              stream: _savebloc.saveInfoStream,
              builder: (context, AsyncSnapshot<BaseResp> snapshot) {
                return FlatButton(
                  padding: EdgeInsets.only(left: 20.0),
                  onPressed: () async {
                    var params = {
                      'id': '59',
                      'headImg': backImageUrl,
                      'username': _nickName,
                      'sex': _sexValue,
                      'birthday': date.toString()
                    };
                    await _save(params);

                    if (snapshot.data?.code == 11002 ||
                        snapshot.data?.code == 11003 ||
                        snapshot.data?.code == 11004) {
                      showMsgDialog(
                          context: context,
                          child: CupertinoAlertDialog(
                            title: Text('提示'),
                            content: Text(snapshot.data.msg),
                            actions: <Widget>[
                              CupertinoDialogAction(
                                child: Text('知道了'),
                                isDestructiveAction: true,
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              )
                            ],
                          ));
                    }
//                    snapshot.data?.code = null;
                  },
                  child: Text('完成', style: TextStyle(fontSize: 17.0)),
                );
              },
            )
          ],
        ),
        body: StreamBuilder(
          stream: _bloc.upLoadImgStream,
          builder: (context, AsyncSnapshot<BaseResp> snapshot) {
            if (snapshot.data?.code == 200) {
              backImageUrl = snapshot.data.data;
              snapshot.data?.code = null;
            }
            return Padding(
                padding: const EdgeInsets.only(top: 20.0),
                child: Column(
                  children: <Widget>[
                    _avatarContainer(),
                    _line(),
                    _nickNameContainer(),
                    _line(),
                    _sexContainer(),
                    _line(),
                    _birthContainer()
                  ],
                ));
          },
        ));
  }

  _uploadImage(File image) async {
    String path = image.path;
    print(path);
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
    FormData formData = new FormData.from({
      "file": new UploadFileInfo(new File(path), name,
          contentType: ContentType.parse("image/$suffix"))
    });
    _uploadImgUrl(formData);
  }

  // 底部actionsheet
  Widget _buildBottomPicker(Widget picker) {
    return Container(
      height: _kPickerSheetHeight,
      padding: const EdgeInsets.only(top: 6.0),
      color: CupertinoColors.white,
      child: DefaultTextStyle(
        style: const TextStyle(
          color: CupertinoColors.black,
          fontSize: 22.0,
        ),
        child: GestureDetector(
          onTap: () {},
          child: SafeArea(
            top: false,
            child: picker,
          ),
        ),
      ),
    );
  }

  // 分割线
  Widget _line() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(22.0, 0.0, 22.0, 0.0),
      child: Divider(
        height: 1.0,
        color: Color.fromRGBO(208, 208, 208, .5),
      ),
    );
  }

  // 头像  3层  1层菊花  2层图片  3层按钮
  Widget _avatarContainer() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.fromLTRB(22.0, 10.0, 20.0, 9.0),
      child: Row(
        children: <Widget>[
          Container(
            height: 51.0,
            alignment: Alignment.center,
            child: Text(
              '头像',
              style: TextStyle(fontSize: 15.0),
            ),
          ),
          Spacer(),
          Container(
            width: 51.0,
            height: 51.0,
            child: Stack(
              children: <Widget>[
                Positioned(
                    top: 18.0,
                    right: 13.0,
                    child: CupertinoActivityIndicator()),
                Positioned(
                  top: 0,
                  right: 0,
                  child: Container(
                    width: 51.0,
                    height: 51.0,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(51.0),
                        image: DecorationImage(
                            fit: BoxFit.cover,
                            image: _image == null
                                ? NetworkImage(
                                    'https://yimg.vip/images/BhBNJaHW.png?imageView2/1/w/80/h/80')
                                : FileImage(_image))),
                  ),
                ),
                Positioned(
                  top: 0.0,
                  right: 0.0,
                  child: FlatButton(
                    onPressed: () {
                      showPersonalActionSheet(
                          context: context,
                          child: CupertinoActionSheet(
                            actions: <Widget>[
                              CupertinoActionSheetAction(
                                child: Text('拍照'),
                                onPressed: getCameraImage,
                              ),
                              CupertinoActionSheetAction(
                                child: Text('我的相册'),
                                onPressed: getGalleryImage,
                              )
                            ],
                            cancelButton: CupertinoActionSheetAction(
                              child: Text('取消',
                                  style: TextStyle(color: Colors.red)),
                              isDefaultAction: true,
                              onPressed: () {
                                Navigator.pop(context, '取消');
                              },
                            ),
                          ));
                    },
                    child: null,
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  // 昵称
  Widget _nickNameContainer() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.fromLTRB(22.0, 0.0, 20.0, 0.0),
      child: Row(
        children: <Widget>[
          Container(
            height: 50.0,
            alignment: Alignment.center,
            child: Text(
              '昵称',
              style: TextStyle(fontSize: 15.0),
            ),
          ),
          Spacer(),
          Container(
            width: 100.0,
            child: TextField(
                decoration: null,
                textAlign: TextAlign.right,
                controller: TextEditingController(text: _nickName),
                onChanged: (text) {
                  setState(() {
                    _nickName = text;
                  });
                },
                style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1))),
          )
        ],
      ),
    );
  }

  // 性别
  Widget _sexContainer() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.fromLTRB(22.0, 0.0, 20.0, 0.0),
      child: Row(
        children: <Widget>[
          Container(
            height: 50.0,
            alignment: Alignment.center,
            child: Text(
              '性别',
              style: TextStyle(fontSize: 15.0),
            ),
          ),
          Spacer(),
          FlatButton(
            padding: EdgeInsets.only(left: 50.0),
            onPressed: () {
              showPersonalActionSheet(
                  context: context,
                  child: CupertinoActionSheet(
                    title: Text('性别'),
                    actions: <Widget>[
                      CupertinoActionSheetAction(
                        child: Text('男'),
                        onPressed: () {
                          setState(() {
                            _sex = '男';
                            _sexValue = '1';
                          });
                          Navigator.pop(context, '男');
                        },
                      ),
                      CupertinoActionSheetAction(
                        child: Text('女'),
                        onPressed: () {
                          setState(() {
                            _sex = '女';
                            _sexValue = '2';
                          });
                          Navigator.pop(context, '女');
                        },
                      )
                    ],
                    cancelButton: CupertinoActionSheetAction(
                      child: Text('取消', style: TextStyle(color: Colors.red)),
                      isDefaultAction: true,
                      onPressed: () {
                        Navigator.pop(context, '取消');
                      },
                    ),
                  ));
            },
            child: Row(
              children: <Widget>[
                Text(_sex,
                    style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1))),
                Icon(Icons.chevron_right)
              ],
            ),
          )
        ],
      ),
    );
  }

  // 出生日期
  Widget _birthContainer() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.fromLTRB(22.0, 0.0, 20.0, 0.0),
      child: Row(
        children: <Widget>[
          Container(
            height: 50.0,
            alignment: Alignment.center,
            child: Text(
              '出生日期',
              style: TextStyle(fontSize: 15.0),
            ),
          ),
          Spacer(),
          FlatButton(
            padding: EdgeInsets.only(left: 50.0),
            onPressed: () {
              showCupertinoModalPopup<void>(
                context: context,
                builder: (BuildContext context) {
                  return _buildBottomPicker(
                    CupertinoDatePicker(
                      mode: CupertinoDatePickerMode.date,
                      initialDateTime: date,
                      onDateTimeChanged: (DateTime newDateTime) {
                        setState(() => date = newDateTime);
                      },
                    ),
                  );
                },
              );
            },
            child: Row(
              children: <Widget>[
                Text(
                    DateUtils.getDateStrByDateTime(date,
                        format: DateFormat.YEAR_MONTH_DAY),
                    style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1))),
                Icon(Icons.chevron_right)
              ],
            ),
          )
        ],
      ),
    );
  }
}
